package com.qf.sy2103.springboot.Controller.User;



import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.ShearCaptcha;
import com.qf.sy2103.springboot.Service.UserService;
import com.qf.sy2103.springboot.Util.Constant;
import com.qf.sy2103.springboot.entity.User;
import com.qf.sy2103.springboot.vo.Tablevo;
import com.qf.sy2103.springboot.vo.Uservo;
import com.qf.sy2103.springboot.vo.pagevo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.util.List;
import java.util.Objects;
import java.util.UUID;

@Slf4j
@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;


    @RequestMapping("/login")
    public String login(HttpServletRequest request){
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        if (password.equals("123")){
            request.getSession().setAttribute("user",username);
            return "1";
        }else{
            return "登录失败";
        }
    }


    //生成验证码
    @RequestMapping("code")
    public void code(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //生成验证码
        ShearCaptcha captcha = CaptchaUtil.createShearCaptcha(200, 100, 4, 4);
        String code=captcha.getCode();//获取到生成的验证码
        //将验证码存在作用域中
        req.getSession().setAttribute("code",code);
//        System.out.println(code);
        captcha.write(resp.getOutputStream());
    }

//    //登录的接口
//    @ResponseBody
//    @RequestMapping("/login")
//    public Uservo login (String real_name, String password, String cap, HttpServletRequest request, HttpSession session) throws IOException {
//        log.info("用户名和密码还有验证码分别是 {} {} {}",real_name,password,cap);
//        Uservo uservo = new Uservo();
//        //获取servlet中生成的验证码
//        String code = (String) session.getAttribute("code");//hutool的验证码
//        // String captcha = (String) session.getAttribute("captcha");//谷歌的验证码
//        if (!(cap.equalsIgnoreCase(code))){
//            uservo.setStatus(Constant.USER_LOGIN_FALE);
//           uservo.setMessage(Constant.USER_MSG_CODEFILE);
//            return uservo;
//        }
//        User user = userService.findUser(real_name, password);
//
//        if (Objects.isNull(user)){
//            uservo.setStatus(Constant.USER_LOGIN_NON);
//            uservo.setMessage(Constant.USER_MSG_NOTFIND);
//            return uservo;
//        }
//        //向session中存储登录数据 判断是否可以查询用户
//        uservo.setStatus(Constant.USER_LOGIN_SUCCESS);
//        uservo.setMessage(Constant.USER_MSGL_SUCCESS);
//        uservo.setUser(user);
//        session.setAttribute("user",uservo);
//        return uservo;
//    }

    //注册的逻辑
    @ResponseBody
    @RequestMapping("/regist")
    public Uservo regist(User user,MultipartFile source, HttpServletRequest request, HttpSession session) throws IOException {
        log.info(user.toString());
        log.info("文件名是 {}",source);
        Uservo uservo = new Uservo();
        if (user.getReal_name().equals("")||user.getPassword().equals("")||user.getEmail().equals("")){
            uservo.setStatus(Constant.USER_REGIST_FALE);
            uservo.setMessage(Constant.USER_MSG_FALE);
            return uservo;
        }
        //上传文件的原始名
        String originalFilename = source.getOriginalFilename();
        //获取上传文件的后缀
        String s = FilenameUtils.getExtension(originalFilename);
        log.info("文件的后缀为 {}",s);
        //生成新的唯一名字
        String newName = UUID.randomUUID().toString();
        //定制全局唯一文件名
        String Name  = newName+"."+s;
        //文件的类型
        String type = source.getContentType();
        log.info("文件名是：{}",Name+"文件类型是：{}",type);
        //获得 upload_file的磁盘路径
//        String realPath = session.getServletContext().getRealPath("/templates");
        String realPath = "I:/pic";
        File file = new File(realPath);
        if (file.exists()){
            file.mkdirs();
        }
        //将上传的文件存入磁盘路径中
        source.transferTo(new File(realPath+"\\"+Name));
        log.info(realPath+"\\"+Name);

        //下面的逻辑就是注册
        String name = user.getReal_name();
        User user1 = userService.selectUser(name);
            //如果查询到这个用户名存在 就返回一个用户名存在的页面
            if (Objects.nonNull(user1)){
                uservo.setStatus(Constant.USER_REGIST_FALE);
                uservo.setMessage(Constant.USER_MSG_NAMEIN);
                return uservo;
            }
            user.setFilename(Name);
            int i = userService.addUser(user);
//            session.invalidate();
            uservo.setStatus(Constant.USER_REGIST_SUCCESS);
            uservo.setMessage(Constant.USER_MSG_SUCCESS);
            uservo.setUser(user);
            return uservo;
    }

    //分页展示返回的数据
    @ResponseBody
    @RequestMapping("/getAll")
    public Tablevo<User> getAll(pagevo pagevo, User user, String statuss){
        log.info("入参是 {}",pagevo,user,statuss);
        //在只传回名字的时候发现问题 最后发现是 layui会将不赋值的数据 传回一个"" 导致只传回一个会报错
        //所以在传回数据的时候 进行判断破将数据赋值给实体类
        if (statuss!=null && statuss!=""){
            int i = Integer.parseInt("statuss");
            user.setStatus(i);
        }
        Tablevo<User> tablevo = userService.getALLUser(pagevo,user);
        log.info("返回的数据是 {}",tablevo);
        return tablevo;
    }

    //向数据库中增加数据 注意在layui传回参数的时候 如果没有填参数 就会直接附一个空的自付出进来
    //并不会返回null报空
    @ResponseBody
    @RequestMapping("/add")
    public Uservo addUser(User user,MultipartFile source,HttpSession session) throws IOException {
        log.info("入参为 {} {}",user,source);

        User user1 = userService.selectUser(user.getReal_name());
        if (Objects.nonNull(user1)){
            Uservo uservo = new Uservo();
            uservo.setMessage(Constant.USER_MSG_NAMEIN);
            return uservo;
        }

        if (Objects.nonNull(source)){
            //上传文件的原始名
            String originalFilename = source.getOriginalFilename();
            //获取上传文件的后缀
            String s = FilenameUtils.getExtension(originalFilename);
            log.info("文件的后缀为 {}",s);
            //生成新的唯一名字
            String newName = UUID.randomUUID().toString();
            //定制全局唯一文件名
            String Name  = newName+"."+s;
            //文件的类型
            String type = source.getContentType();
            log.info("文件名是：{}",Name+"文件类型是：{}",type);
            //获得 upload_file的磁盘路径
            String realPath = session.getServletContext().getRealPath("/upload_file");

            File file = new File(realPath);
            if (file.exists()){
                file.mkdirs();
            }
            //将上传的文件存入磁盘路径中
            source.transferTo(new File(realPath+"\\"+Name));
            log.info(realPath+"\\"+Name);
            user.setFilename(Name);
        }

        Uservo uservo = new Uservo();
        if (Objects.isNull(user)){
            //如果修改失败就什么都不给前端的判定if（）空的话就会执行else
            uservo.setMessage(Constant.USER_VIEWS_FULE);
            return uservo;
        }

        uservo.setStatus(Constant.USER_VIEWS_SUCCESS);
        uservo.setMessage(Constant.USER_VIEWS_SUCCES);
        int i = userService.addUser(user);
        log.info("增加成功 {}",i);
        return uservo;
    }

    @ResponseBody
    @RequestMapping("/del")
    //删除数据数据ids
    public Uservo deleteUser(@RequestParam(value = "ids",required = false) List<Integer> ids){
        log.info("入参为 {}",ids);
        Uservo uservo = new Uservo();
        //调用service层逻辑进行删除
        int i =  userService.deleteUser(ids);
        if (i==0){
            log.info("删除失败");
            uservo.setMessage(Constant.USER_DELETE_FALES);
            return uservo;
//            return "/user/getAll";
        }
        uservo.setStatus(Constant.USER_DELETE_SUCCESS);
        uservo.setMessage(Constant.USER_DELETE_SUCCES);
        log.info("删除成功");
//        return "/user/getAll";
        return uservo;
    }


    //修改数据
    @ResponseBody
    @RequestMapping("/update")
    public Uservo updateUser(MultipartFile source,HttpSession session,String real_name,String password,String email,Integer id) throws IOException {
        //判断用户名是否重复
        Uservo uservo = new Uservo();

        User user1 = userService.selectUser(real_name);
        if (Objects.nonNull(user1)){
            uservo.setMessage(Constant.CLIENT_ADD_FILL+"请修改用户名称或清空用户名");
            return uservo;
        }
        User user = new User();
               user.setId(id);
               user.setReal_name(real_name);
               user.setPassword(password);
               user.setEmail(email);
        log.info("入参为 {} {}",user,source);
        //,MultipartFile source,HttpSession session

        if (source.getSize()!=0){
            //上传文件的原始名
            String originalFilename = source.getOriginalFilename();
            //获取上传文件的后缀
            String s = FilenameUtils.getExtension(originalFilename);
            log.info("文件的后缀为 {}",s);
            //生成新的唯一名字
            String newName = UUID.randomUUID().toString();
            //定制全局唯一文件名
            String Name  = newName+"."+s;
            //文件的类型
            String type = source.getContentType();
            log.info("文件名是：{}",Name+"文件类型是：{}",type);
            //获得 upload_file的磁盘路径
//            String realPath = session.getServletContext().getRealPath("/templates");
            String realPath = "I:/pic";
            File file = new File(realPath);
            if (file.exists()){
                file.mkdirs();
            }
            //如果修改了头像就存入user里
            user.setFilename(Name);
            //将上传的文件存入磁盘路径中
            source.transferTo(new File(realPath+"\\"+Name));
            log.info(realPath+"\\"+Name);
        }


        int i = userService.updateUser(user);
        if (i==0){
            log.info("修改失败");
            uservo.setMessage(Constant.USER_UPDATE_FALES);
            return uservo;
//            return "/user/getAll";
        }
        uservo.setStatus(Constant.USER_UPDATE_SUCCESS);
        uservo.setMessage(Constant.USER_UPDATE_SUCCES);
        log.info("修改成功");
//        return "/user/getAll";
        return uservo;
    }

    //主页的用户信息
    @ResponseBody
    @RequestMapping("/inuser")
    public User inuser(HttpSession session){
        //获取在登录时在session中存储的数据
        Uservo uservo = (Uservo) session.getAttribute("user");
        User user = uservo.getUser();
        log.debug("当前用户的信息是 {}",user);
        return user;
    }

    //获取用户的头像
    @RequestMapping("/img")
    public void img(String filename,HttpServletRequest request, HttpServletResponse response) throws IOException {
        //获取要下载文件的绝对路径 无论在什么操作系统都可以使用
//        String path = request.getServletContext().getRealPath("/templates");
        String path = "I:/pic";
        String real_path = path+"\\"+filename;//获取要下载系统的真实路径
        log.debug("返回图片的路径是 {}",real_path);
        IOUtils.copy(new FileInputStream(real_path),response.getOutputStream());
    }

    //返回导出全部文件文件名
    @ResponseBody
    @RequestMapping("/showAll")
    public Uservo showAll(HttpServletRequest request,HttpServletResponse response) throws IOException {
        Uservo uservo = new Uservo();
        String path = request.getServletContext().getRealPath("upload_file");
       String realpath =  userService.writeinformation(path);
//        String real_path = realPath+"\\"+"1.txt";
//        IOUtils.copy(new FileInputStream("1.txt"),response.getOutputStream());
        uservo.setFilename(realpath);
        return uservo;
    }



    //返回下载全部信息的txt
    @RequestMapping("/download")
    public void download(String filename,HttpServletRequest request,HttpServletResponse response) throws IOException {
//        userService.writeinformation();
        String realPath = request.getServletContext().getRealPath("upload_file");
        String real_path = realPath+"\\"+filename;
        response.setHeader("content-disposition","attachment;filename="+filename);
        IOUtils.copy(new FileInputStream(real_path),response.getOutputStream());
    }
}
